package service;

import com.alibaba.fastjson.JSONObject;
import entity.GameRoom;
import entity.Player;

import java.util.concurrent.ConcurrentHashMap;
import java.util.function.BiConsumer;

import static service.Message.getRoomAbstractJson;

public class GameRoomServiceImp implements GameRoomService {

    private static GameRoomServiceImp gameRoomServiceImp = new GameRoomServiceImp();

    public static GameRoomServiceImp getGameRoomServiceImp() { return gameRoomServiceImp; }

    private GameRoomServiceImp() {
        rooms = new ConcurrentHashMap<>();
    }

    private ConcurrentHashMap<Long, GameRoom> rooms;

    @Override
    public final JSONObject getRoomAbstractListJson() {

        JSONObject json = new JSONObject();
        JSONObject jsonArr[] = new JSONObject[rooms.size()];

        rooms.forEach(new BiConsumer<Long, GameRoom>() {
            private int i = 0;
            @Override
            public void accept(Long aLong, GameRoom gameRoom) {
                if(gameRoom.isVisible()) {
                    if(gameRoom.isWatchable() || gameRoom.getPlayerCount() < 2)
                        jsonArr[i++] = getRoomAbstractJson(gameRoom);
                }
            }
        });
        json.put("room_list", jsonArr);

        return json;
    }

    @Override
    public final GameRoom createRoom(String title, Player host, String passwordHash) {
        GameRoom r = new GameRoom(title, host, passwordHash);
        rooms.put(r.getId(), r);
        //System.out.println("creeated room " + title);
        return r;
    }

    /**
     * 关闭房间
     * @param r 要关闭的房间
     * @return 成功返回关闭的房间，失败返回null
     */
    @Override
    public final GameRoom removeRoom(GameRoom r) {
        GameRoom ret = null;
        if(r.getPlayerCount() == 0) {
            ret = rooms.remove(r.getId());
        }
        return ret;
    }

    @Override
    public GameRoom getRoom(Long roomId) {
        return rooms.get(roomId);
    }
}
